//
//  accountViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/2/19.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "accountViewController.h"
#import "UIViewExt.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
@interface accountViewController ()<UITextFieldDelegate>
{
    NSString *zhifubaoStr;
    UITextField *accountField;
    UITextField *moneyField;
    UITextField *passwordField;
    UILabel *balanceLable;
    UIButton *tixian;
}
@property (strong, nonatomic) UIButton *rightButton;
@end

@implementation accountViewController
- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"账户余额";
    // Do any additional setup after loading the view.
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"zhifubao"]) {
        zhifubaoStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"zhifubao"];
    } else {
        zhifubaoStr = nil;
    }
    
    
    [self createNavigationView];
    [self createSubiews];
}
- (void)createNavigationView
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.tag = 36;
        [leftButton setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    [leftButton addTarget:self action:@selector(touchNavigationButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
}
- (void)createSubiews
{
//    支付宝账号
    UIView *accountView = [[UIView alloc] initWithFrame:CGRectMake(25, 0, self.view.width - 100, 44)];
    [self.view addSubview:accountView];
   
    UILabel *accountLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, accountView.width, accountView.height)];
    accountLable.text = @"支付宝账户";
    accountLable.font = [UIFont systemFontOfSize:17];
    accountLable.textColor = [UIColor blackColor];
    [accountView addSubview:accountLable];
    
    CGSize size = [self sizeWithFont:accountLable.font maxSize:CGSizeMake(accountLable.width, accountLable.height) text:accountLable.text];
    accountField = [[UITextField alloc] initWithFrame:CGRectMake(size.width + 30, 5, accountView.width - size.width, size.height)];
    accountField.center = CGPointMake(accountField.center.x, accountLable.center.y);
    accountField.text = zhifubaoStr;
    accountField.delegate = self;
    accountField.placeholder = @"请输入支付宝账号";
    accountField.keyboardType = UIKeyboardTypeASCIICapable;
    accountField.returnKeyType = UIReturnKeyNext;
    [accountView addSubview:accountField];
    
    UIImageView *preferencesLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, accountView.bottom, self.view.width, 1)];
    preferencesLine.image = [UIImage imageNamed:@"gray_line"];
    [self.view addSubview:preferencesLine];
//提现金额
    UIView *moneyView = [[UIView alloc] initWithFrame:CGRectMake(25, accountView.bottom, accountView.width, accountView.height)];
    [self.view addSubview:moneyView];
    UILabel *moneyLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, moneyView.width, moneyView.height)];
    moneyLable.text = @"转出金额";
    moneyLable.font = [UIFont systemFontOfSize:17];
    moneyLable.textColor = [UIColor blackColor];
    [moneyView addSubview:moneyLable];
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(size.width, 0, 30, moneyLable.height)];

    lable.text = @"¥";
    lable.font = [UIFont boldSystemFontOfSize:17];
    lable.textColor = [UIColor blackColor];
    [moneyView addSubview:lable];
    moneyField = [[UITextField alloc] initWithFrame:CGRectMake(lable.right, 0, self.view.width - lable.right, lable.height)];
    moneyField.font = [UIFont systemFontOfSize:17];
    moneyField.keyboardType = UIKeyboardTypeDecimalPad;
    moneyField.placeholder = @"请输入金额";
    moneyField.delegate = self;
    [moneyField addTarget:self action:@selector(textfieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [moneyView addSubview:moneyField];
    UIImageView *moneyLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, moneyView.bottom, self.view.width, 1)];
    moneyLine.image = [UIImage imageNamed:@"gray_line"];
    [self.view addSubview:moneyLine];
//    密码
    UIView *passwordView = [[UIView alloc] initWithFrame:CGRectMake(25, moneyView.bottom, moneyView.width, moneyView.height)];
    [self.view addSubview:passwordView];
    UILabel *passwordTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, passwordView.width, passwordView.height)];
    passwordTitle.text = @"登录密码";
    passwordTitle.font = [UIFont systemFontOfSize:17];
    passwordTitle.textColor = [UIColor blackColor];
    [passwordView addSubview:passwordTitle];
    passwordField = [[UITextField alloc] initWithFrame:CGRectMake(lable.right, 0, self.view.width - lable.right, lable.height)];
    passwordField.font = [UIFont systemFontOfSize:17];
    passwordField.placeholder = @"请输入声音实验室登录密码";
    passwordField.delegate = self;
    passwordField.secureTextEntry = YES;
    [passwordView addSubview:passwordField];
    UIImageView *passwordLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, passwordView.bottom, self.view.width, 1)];
    passwordLine.image = [UIImage imageNamed:@"gray_line"];
    [self.view addSubview:passwordLine];
//账户余额
    UIView *balanceView = [[UIView alloc] initWithFrame:CGRectMake(25, passwordView.bottom, moneyView.width, 35)];
    [self.view addSubview:balanceView];
    UILabel *balanceTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, balanceView.width, balanceView.height)];
    balanceTitle.text = @"账户余额";
    balanceTitle.font =[UIFont systemFontOfSize:12];
    balanceTitle.textColor = [UIColor grayColor];
    [balanceView addSubview:balanceTitle];
    CGSize balanceSize = [self sizeWithFont:balanceTitle.font maxSize:balanceTitle.bounds.size text:balanceTitle.text];
    balanceLable = [[UILabel alloc] initWithFrame:CGRectMake(balanceSize.width + 10, 0, balanceView.width - balanceSize.width - 10, balanceView.height)];
    balanceLable.text = [NSString stringWithFormat:@"¥%@",_balance];
    balanceLable.font =[UIFont systemFontOfSize:12];
    balanceLable.textColor = [UIColor grayColor];
    [balanceView addSubview:balanceLable];
    
    UIImageView *balanceLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, balanceView.bottom, self.view.width, 1)];
    balanceLine.image = [UIImage imageNamed:@"gray_line"];
    [self.view addSubview:balanceLine];
    
    UILabel *limLable = [[UILabel alloc] initWithFrame:CGRectMake(0, balanceLine.bottom + 10, self.view.width,40)];
    limLable.text = @"一周内可提现一次，提现金额不得小于2元；\n提现金额小于100元收取2元手续费，大于100元免手续费";
    limLable.font = [UIFont systemFontOfSize:12];
    limLable.textColor = [UIColor grayColor];
    limLable.textAlignment = NSTextAlignmentCenter;
    limLable.numberOfLines = 0;
    limLable.lineBreakMode = NSLineBreakByWordWrapping;
    [self.view addSubview:limLable];
    
    tixian = [UIButton buttonWithType:UIButtonTypeCustom];
    tixian.frame = CGRectMake(self.view.width / 4, limLable.bottom + 10, self.view.width / 2, 44);
//    tixian.center = CGPointMake(self.view.center.x, limLable.center.y + 60);
    [tixian setTitle:@"确认转出" forState: UIControlStateNormal];
    [tixian setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [tixian addTarget:self action:@selector(tixianClick:) forControlEvents:UIControlEventTouchUpInside];
    tixian.layer.borderColor = [[UIColor grayColor]CGColor];
    tixian.layer.borderWidth = 2;
    tixian.userInteractionEnabled = NO;
    [self.view addSubview:tixian];
    UILabel *errorLable = nil;
    if (_isPayEnable == 0) {
        errorLable = [[UILabel alloc] initWithFrame:CGRectMake(0, tixian.bottom + 20, self.view.width, 20)];
        errorLable.text = @"7天内仅可提现一次";
        errorLable.font = [UIFont boldSystemFontOfSize:16];
        errorLable.textAlignment = NSTextAlignmentCenter;
        errorLable.textColor = [UIColor redColor];
        [self.view addSubview:errorLable];
    }
    
    if (accountField.text) {
        [moneyField becomeFirstResponder];
    } else {
        [accountField becomeFirstResponder];
    }
}

- (void)touchNavigationButton
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)tixianClick:(UIButton *)sender
{
    if ([[moneyField.text substringFromIndex:moneyField.text.length - 1] isEqualToString:@"."]) {
        moneyField.text = [moneyField.text stringByReplacingOccurrencesOfString:@"." withString:@""];
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:accountField.text,@"alipay",[NSNumber numberWithFloat:moneyField.text.floatValue],@"cash",passwordField.text,@"password", nil];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *str = @"http://123.57.1.143/api/cash/refer";
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        if ([[responseObject valueForKey:@"status"] boolValue] == YES) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeAccount" object:moneyField.text];
            [[NSUserDefaults standardUserDefaults] setValue:accountField.text forKey:@"zhifubao"];
            [self touchNavigationButton];
        } else {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"登陆密码输入错误" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == moneyField) {
        if ([string  isEqual: @""]) {
            return YES;
        }
        NSMutableString * futureString = [NSMutableString stringWithString:textField.text];
        [futureString  insertString:string atIndex:range.location];
        NSInteger flag=0;
        const NSInteger limited = 1;
        for (int i = (int)futureString.length-1; i>=0; i--) {
            if ([futureString characterAtIndex:i] == '.') {
                if (flag > limited) {
                    return NO;
                }
                break;
            }
            flag++;
        }
        return YES;
    } else {
        return YES;
    }
}
- (void)textfieldEditingChanged:(UITextField *)field
{
    
    if (moneyField.text.floatValue > 2.00 && accountField.text.length > 0 && _isPayEnable == 1) {
//        NSLog(@"%f",textField.text.floatValue);
        if (moneyField.text.floatValue > _balance.floatValue) {
            moneyField.text = _balance;
        }
        [tixian setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        tixian.layer.borderColor = [[UIColor blackColor]CGColor];
        tixian.layer.borderWidth = 2;
        tixian.userInteractionEnabled = YES;
    } else {
//        NSLog(@"%f",textField.text.floatValue);
        
        [tixian setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        tixian.layer.borderColor = [[UIColor grayColor] CGColor];
        tixian.layer.borderWidth = 2;
        tixian.userInteractionEnabled = NO;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == accountField) {
        [moneyField becomeFirstResponder];
    }
    return YES;
}

-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize text:(NSString *)text
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
